package com.cwj.mansysback.servlet.util;

import com.cwj.mansysback.servlet.impl.Statement;
import com.google.gson.Gson;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class MyUtils {

    public static <T> T transform(Class<T> clazz, HttpServletRequest req) {

        T t = null;
        try {
            t = clazz.getConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }

        final Field[] declaredFields = clazz.getDeclaredFields();

        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            if (req.getParameter(name) != null) {
                declaredField.setAccessible(true);
                try {
                    declaredField.set(t, req.getParameter(name));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return t;
    }

    public static String createKey(int length) {

        String KeyString = "123456789abcdefghijklmnopqrstuvwxyz";
        int len = KeyString.length();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<length;i++){
            sb.append(KeyString.charAt((int) Math.round(Math.random()*(len-1))));
        }
        return sb.toString();
    }

    public static void writeResponse (ServletResponse response, Object statue){

        if(statue == null ){
            MyUtils.writeResponse(response,new Statement(7));
            return ;
        }

        // 2.创建Gson对象
        Gson gson = new Gson();

        System.out.println(statue);

        // 3.将Java对象转换为JSON对象
        String json = gson.toJson(statue);

        // 4.设置响应体的内容类型
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getMethodName(String fieldName){
        return "set"+Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1);
    }


}
